#include "Precompile.h"
#include "PhysicsSystemPhysX.h"

namespace Physics{
	PhysicsSystemPhysX::PhysicsSystemPhysX():m_physicsSDK(NULL){
		m_ready = true;
		m_runThread = ThreadLib::ThreadFactory::spawnThread(boost::function<void(void)>(boost::bind(&PhysicsSystemPhysX::update,this)));
		initialize();
	}

	PhysicsSystemPhysX::~PhysicsSystemPhysX(){
		if(m_physicsSDK)
			m_physicsSDK->release();
	}

	void PhysicsSystemPhysX::step(float step){
		/*if(!m_ready)
			return;

		m_ready = false;
		m_step = step;
		m_runThread->run();*/
	}

	void PhysicsSystemPhysX::initialize(){
		m_physicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL);
		if(!m_physicsSDK){
			LOG_ERROR("Failed in creating a physX device.");
		}
	}

	void PhysicsSystemPhysX::update(){
		std::map<unsigned int,NxScene*>::iterator itr = m_scenes.begin();
		NxU32 numTransforms;
		NxActiveTransform *transforms;
		m_transforms.clear();
		
		while(itr != m_scenes.end()){
			numTransforms = 0;
			itr->second->fetchResults(NxSimulationStatus::NX_ALL_FINISHED,true);
			transforms = itr->second->getActiveTransforms(numTransforms);
			m_transforms[itr->first] = std::pair<unsigned int,NxActiveTransform*>(numTransforms,transforms);
			
			itr++;
		}

		m_ready = true;
	}

	std::vector<int> PhysicsSystemPhysX::rayCast(int sceneId, Utility::Math::Vector<> &from,Utility::Math::Vector<> &dir){
		std::vector<int> hits;

		return hits;
	}
}